package com.fjwt.gz.coupon.hkpay;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.hkpay.hkpayutil.HkApiClient;
import com.fjwt.gz.coupon.SendCouponBo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 海科发券
 */
@Slf4j
@Service
public class HkpayCouponSendService {
    //TODO 注意： 上面记得封装一层，统一调用，通过不同通道调用不同的逻辑，
    private static final Logger hkPayLogger = LoggerFactory.getLogger("hkPay");


    public JSONObject couponSend(SendCouponBo sendCouponBo) {
        String logPrefix = "【海科支付通道发券】";

        hkPayLogger.info("{},进来的参数是：{}", JSONUtil.toJsonStr(sendCouponBo));

        if (Objects.isNull(sendCouponBo)) {
            throw new BizException("发券参数缺失！");
        }
        JSONObject reqJson = new JSONObject();
        reqJson.put("stockId", sendCouponBo.getStockId());
        reqJson.put("orderNo", DateUtil.date().getTime());
        reqJson.put("openId", sendCouponBo.getOpenId());

        JSONObject hkAuthConfig = sendCouponBo.getAuthConfig();
        hkPayLogger.info("{},配置参数：{}", logPrefix, JSONUtil.toJsonStr(hkAuthConfig));
        reqJson.put("appId", hkAuthConfig.getString("appId"));

        try {
            HkApiClient apiClient = new HkApiClient(hkAuthConfig.getString("clientKey"), hkAuthConfig.getString("securityKey"), hkAuthConfig.getString("address"));
            HkApiClient.ApiResponse<JSONObject> response = apiClient.request(hkAuthConfig.getString("service"), hkAuthConfig.getString("version"), hkAuthConfig.getString("name"), reqJson, JSONObject.class);
            hkPayLogger.info("{} 请求参数：reqJson={},请求结果：respJson={}", logPrefix, JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));

            if (response == null) {
                hkPayLogger.info("{} 请求失败,返回内容为空，请求参数：reqJson={}", logPrefix, JSONUtil.toJsonStr(reqJson));
                throw new BizException("发券失败");
            }

            if (!"0".equals(response.getCode())) {
                hkPayLogger.info("{} 请求失败，请求参数：reqMap={},返回参数：{}", logPrefix, JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));
                throw new BizException("发券失败");
            }

            if (response.getData() == null) {
                hkPayLogger.info("{} 请求失败,返回data内容为空，返回参数：{}", logPrefix, JSONUtil.toJsonStr(response));
                throw new BizException("发券失败");
            }
            hkPayLogger.info("{},发券接口返回数据是：{}", logPrefix, JSONUtil.toJsonStr(response.getData()));
            return response.getData();

        } catch (BizException e) {
            hkPayLogger.info("海科发券失败");
            throw e;
        } catch (Exception e) {
            hkPayLogger.info("海科发券失败");
            e.printStackTrace();
        }

        return null;
    }

}
